<script>
import { ElMessage, genFileId } from "element-plus";
import { Clock, Plus } from "@element-plus/icons-vue";
import store from "../../store/index.js";
import request from "../../utils/Request.js";

export default {
  name: "settingProjectDialog",
  computed: {
    store() {
      return store;
    },
    settingProjectDialogVisible() {
      return store.state.settingProjectDialogVisible;
    },
    memberInProject() {
      if (this.addMember != null)
        for (let m of this.projectMembers) {
          if (m.id === this.addMember.id) return true;
        }
      return false;
    },
  },
  components: { Clock, Plus },
  data() {
    return {
      addMemberDialogVisible: false,
      formData: new FormData(),
      rules: {
        name: [
          {
            validator: (rule, value, callback) => {
              if (!new RegExp("^[\u4e00-\u9fa5_a-zA-Z0-9-]+$").test(value))
                callback(
                  new Error("请输入正确的名称，且不能包含除_-以外的字符！")
                );
              else callback();
            },
          },
        ],
        description: [
          {
            min: 0,
            max: 255,
            message: "简介长度在0到255之间",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (
                value !== "" &&
                !new RegExp("^[\u4e00-\u9fa5_a-zA-Z0-9-,.，。]+$").test(value)
              )
                callback(
                  new Error(
                    "请输入正确的名称，且不能包含除_-,.，。以外的字符！"
                  )
                );
              else callback();
            },
          },
        ],
      },
      projectMembers: [
        // {
        //   id: store.state.user.id,
        //   avatarUrl: store.state.user.avatarUrl,
        //   nickname: store.state.user.nickname,
        //   email: store.state.user.email,
        // },
        // {
        //   id: 1,
        //   avatarUrl: 'https://shiziapi.oss-cn-shenzhen.aliyuncs.com/user_avatars/9.jpg',
        //   nickname: 'Nick',
        //   email: '123@qq.com',
        // },
        // {
        //   id: 2,
        //   avatarUrl: 'https://shiziapi.oss-cn-shenzhen.aliyuncs.com/user_avatars/9.jpg',
        //   nickname: 'Nick',
        //   email: '',
        // },
        // {
        //   id: 3,
        //   avatarUrl: 'https://shiziapi.oss-cn-shenzhen.aliyuncs.com/user_avatars/9.jpg',
        //   nickname: 'Nick',
        //   email: 'wuxinihasid@qq.com',
        // }
      ],
      projectMemberCount: 0,
      currentPage: 1,
      totalPage: 1,
      tempAvatarUrl: null,
      fileReader: new FileReader(),
      disableModifyButton: false,
      addMemberFormData: {
        keyword: "",
      },
      addMemberFormRules: {
        keyword: [
          { required: true, message: "请输入用户ID", trigger: "change" },
          { type: "number", message: "请输入正确的用户ID", trigger: "blur" },
        ],
      },
      addMember: null,
      addMemberLoading: false,
      historyData: [
        // {
        //   editorId: '',
        //   editorName: '',
        //   docId: '',
        //   docName: '',
        //   docType: 0,
        //   editChange: "",
        // }
      ],
      historyPage: {
        // currentPage: 1,
        // totalPage: 1,
        // total: 0,
      },
    };
  },
  methods: {
    onChangeAvatar(uploadFile) {
      let rawFile = uploadFile.raw;
      let upload = this.$refs["uploadRef"];
      if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("图片必须是jpg或png类型的!");
        upload.clearFiles();
        return;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("图片大小不能超过2MB!");
        upload.clearFiles();
        return;
      }
      this.formData.set("file", rawFile);
      this.fileReader.readAsDataURL(rawFile);
    },
    handleExceed(files) {
      let upload = this.$refs["uploadRef"];
      upload.clearFiles();
      const file = files[0];
      file.uid = genFileId();
      upload.handleStart(file);
    },
    modifyProject(project) {
      let form = this.$refs["formRef"];

      form.validate((isValid) => {
        if (isValid) {
          this.disableModifyButton = true;

          this.formData.set("id", project.id);
          this.formData.set("name", project.name);
          this.formData.set("description", project.description);
          this.formData.set("isPrivate", project.isPrivate);

          request({
            method: "post",
            url: "/api/project/project/modify",
            headers: { "Content-Type": "multipart/form-data" },
            data: this.formData,
          })
            .then((resp) => {
              let data = resp.data;
              if (data.code === 0) {
                ElMessage.success("修改成功！");
              } else {
                ElMessage.error(data.msg);
              }
              this.disableModifyButton = false;
            })
            .catch((err) => {
              ElMessage.error("未知错误，请重试");
              this.disableModifyButton = false;
            });
        }
      });
    },
    planeChangeEvent(planeName) {
      console.log(planeName);
      if (planeName === "ProjectMember") {
        if (this.projectMembers == null || this.projectMembers.length === 0) {
          this.getProjectMembers(store.state.settingProject.id, 1);
        }
      } else if (planeName === "ProjectHistory") {
        if (this.historyData == null || this.historyData.length === 0) {
          this.getHistory(store.state.settingProject.id, 1);
        }
      }
    },
    getHistory(projectId, page) {
      this.getMemberLoading = true;
      request({
        method: "post",
        url: "/api/project/project/history/list",
        params: {
          id: projectId,
          page: page,
          limit: 8,
        },
      })
        .then((resp) => {
          let data = resp.data;
          if (data.code === 0) {
            this.historyData = data.data.list;
            this.historyPage.total = data.data.total;
            this.historyPage.totalPage = data.data.totalPage;
            this.historyPage.currentPage = data.data.currentPage;
          } else {
            ElMessage.error(data.msg);
          }
        })
        .catch(() => {
          ElMessage.error("出现未知错误，请稍后再刷新");
        });
    },
    getProjectMembers(projectId, page) {
      this.getMemberLoading = true;
      request({
        method: "get",
        url: "/api/project/project/member",
        params: {
          id: projectId,
          page: page,
          limit: 6,
        },
      })
        .then((resp) => {
          let data = resp.data;
          if (data.code === 0) {
            this.projectMembers = data.data.list;
            this.projectMemberCount = data.data.total;
            this.totalPage = data.data.totalPage;
            this.currentPage = data.data.currentPage;
          } else {
            ElMessage.error(data.msg);
          }
        })
        .catch(() => {
          ElMessage.error("出现未知错误，请稍后再刷新");
        });
    },
    deleteProject() {
      request({
        method: "get",
        url: "/api/project/project/delete",
        params: {
          id: store.state.settingProject.id,
        },
      })
        .then((resp) => {
          let data = resp.data;
          if (data.code === 0) {
            store.state.settingProjectDialogVisible = false;
            ElMessage.success("删除成功！");
          } else {
            ElMessage.error(data.msg);
          }
        })
        .catch(() => {
          ElMessage.error("出现未知错误，请稍后再刷新");
        });
    },
    /**
     * 通过id搜索成员
     */
    searchMember() {
      let form = this.$refs["addMemberForm"];
      form.validate((isValid) => {
        if (isValid) {
          this.addMemberLoading = true;
          request({
            url: "/api/uaa/user/member",
            method: "get",
            params: {
              id: this.addMemberFormData.keyword,
            },
          })
            .then((resp) => {
              let data = resp.data;
              if (data.code === 0) {
                this.addMember = data.data;
              } else {
                ElMessage.error(data.msg);
              }
              this.addMemberLoading = false;
            })
            .catch((err) => {
              ElMessage.error("出现未知错误");
              this.addMemberLoading = false;
            });
        }
      });
    },
    /**
     * 邀请用户进入知识库
     */
    inviteToProject() {
      request({
        url: "/api/project/project/member/invite",
        method: "get",
        params: {
          projectId: store.state.settingProject.id,
          memberId: this.addMember.id,
        },
      }).then((resp) => {
        let data = resp.data;
        if (data.code === 0) {
          this.addMember.invite = true;
        }
      });
    },
    /**
     * 删除一位知识库成员
     * @param memberId
     */
    kickMember(memberId) {
      if (memberId === store.state.user.id) return;

      request({
        url: "/api/project/project/member/kick",
        method: "get",
        params: {
          projectId: store.state.settingProject.id,
          memberId: memberId,
        },
      }).then((resp) => {
        let data = resp.data;
        if (data.code === 0) {
          ElMessage.success("成功踢出ID为" + memberId + "的成员！");
          this.getProjectMembers(
            store.state.settingProject.id,
            this.currentPage
          );
        }
      });
    },
  },
  created() {
    this.fileReader.addEventListener(
      "load",
      () => {
        this.tempAvatarUrl = this.fileReader.result;
      },
      false
    );
  },
  watch: {
    settingProjectDialogVisible(newVal, oldVal) {
      this.tempAvatarUrl = null;
      if (newVal === true && store.state.settingProject.members == null)
        store.state.settingProject.members = [];
    },
  },
};
</script>

<template>
  <el-dialog
    v-model="store.state.settingProjectDialogVisible"
    title="知识库设置"
    width="60%"
    destroy-on-close
    @close="
      projectMembers = [];
      historyData = [];
      historyPage = {};
    "
  >
    <el-tabs
      type="border-card"
      tab-position="left"
      @tab-change="planeChangeEvent"
      model-value="ProjectInfo"
    >
      <el-tab-pane label="知识库信息" name="ProjectInfo">
        <el-form
          ref="formRef"
          :model="store.state.settingProject"
          :rules="rules"
        >
          <el-form-item label="封面">
            <el-image
              :src="
                tempAvatarUrl == null
                  ? store.state.settingProject.coverUrl == null
                    ? '/default_project_cover.png'
                    : store.state.settingProject.coverUrl
                  : tempAvatarUrl
              "
              fit="cover"
              class="w-96 h-128"
              style="border-radius: 5%"
            >
              <template #error>
                <el-image
                  fit="cover"
                  class="w-96 h-128"
                  src="/default_project_cover.png"
                />
              </template>
            </el-image>
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleExceed"
              @change="onChangeAvatar"
              :on-remove="() => this.formData.delete('file')"
              :disabled="store.state.projectType !== 'myProjects'"
              :show-file-list="false"
            >
              <el-button
                type="primary"
                class="ml-20"
                v-if="store.state.projectType === 'myProjects'"
              >
                上传封面
              </el-button>
            </el-upload>
          </el-form-item>

          <el-form-item prop="name" label="知识库名称">
            <el-input
              v-model="store.state.settingProject.name"
              placeholder="知识库名称"
              :disabled="store.state.projectType !== 'myProjects'"
              maxlength="64"
            />
          </el-form-item>

          <el-form-item prop="description" label="知识库简介">
            <el-input
              v-model="store.state.settingProject.description"
              type="textarea"
              placeholder="知识库简介"
              show-word-limit
              :disabled="store.state.projectType !== 'myProjects'"
              maxlength="255"
            />
          </el-form-item>

          <el-form-item prop="isPrivate" label="知识库属性">
            <el-switch
              v-model="store.state.settingProject.isPrivate"
              style="--el-switch-off-color: #13ce66"
              :active-value="1"
              :inactive-value="0"
              active-text="私有"
              inactive-text="公开"
              :disabled="store.state.projectType !== 'myProjects'"
              size="large"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="store.state.projectType === 'myProjects'"
              type="primary"
              :disabled="disableModifyButton"
              @click="modifyProject(store.state.settingProject)"
              >保存修改
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane
        label="知识库成员"
        name="ProjectMember"
        lazy
        v-loading="projectMembers == null || projectMembers.length === 0"
      >
        <el-row>
          <el-col :span="6">
            <el-text style="font-weight: bolder">
              知识库成员 ({{ projectMemberCount }})
            </el-text>
          </el-col>

          <el-col :span="3" :offset="10">
            <el-button
              plain
              type="primary"
              @click="getProjectMembers(store.state.settingProject.id, 1)"
              >刷新
            </el-button>
          </el-col>

          <el-col :span="4" :offset="1">
            <el-button
              plain
              type="primary"
              @click="addMemberDialogVisible = true"
              v-if="store.state.user.id === store.state.settingProject.userId"
              >添加成员</el-button
            >
          </el-col>
        </el-row>
        <el-divider style="margin-bottom: 10px; margin-top: 10px" />

        <el-row
          v-for="user in projectMembers"
          :gutter="5"
          class="m-0 p-0"
          :key="user.id"
        >
          <el-col :span="3">
            <el-avatar :src="user.avatarUrl" />
          </el-col>
          <el-col :span="5">
            <el-text>{{ user.nickname }}</el-text>
          </el-col>
          <el-col :span="3">
            <el-text>{{ user.id }}</el-text>
          </el-col>
          <el-col :span="6">
            <el-text>{{ user.email }}</el-text>
          </el-col>
          <el-col :span="4">
            <el-tag type="success" size="large" v-if="user.type === 2"
              >参与者</el-tag
            >
            <el-tag size="large" v-if="user.type === 1">管理者</el-tag>
            <el-tag type="warning" size="large" v-if="user.type === 0"
              >拥有者</el-tag
            >
          </el-col>
          <el-col
            :span="3"
            v-if="store.state.user.id === store.state.settingProject.userId"
          >
            <el-popconfirm
              :title="'是否要从知识库中踢出ID为' + user.id + '的成员?'"
              @confirm="kickMember(user.id)"
              v-if="user.type !== 0"
            >
              <template #reference>
                <el-button type="danger" plain size="small">踢出 </el-button>
              </template>
            </el-popconfirm>
          </el-col>
          <el-divider style="margin-bottom: 10px; margin-top: 10px" />
        </el-row>

        <el-row>
          <el-col :offset="14">
            <el-pagination
              layout="prev, pager, next"
              :page-count="totalPage"
              v-model:current-page="currentPage"
              size="small"
              @current-change="
                (p) => getProjectMembers(store.state.settingProject.id, p)
              "
            />
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane
        label="知识库记录"
        name="ProjectHistory"
        lazy
        v-loading="historyPage == null || historyPage.length === 0"
      >
        <el-button
          plain
          type="primary"
          style="float: right"
          @click="getHistory(store.state.settingProject.id, historyPage.currentPage || 1)"
          >刷新
        </el-button>

        <el-table :data="historyData" stripe style="width: 100%">
          <el-table-column prop="editChange">
            <template #default="scope">
              {{
                scope.row.editorName +
                "(" +
                scope.row.editorId +
                ")" +
                ": " +
                scope.row.editChange
              }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" fixed="right" :align="'right'" />
        </el-table>
        <el-pagination
          layout="prev, pager, next"
          :page-count="historyPage.totalPage"
          v-model:current-page="historyPage.currentPage"
          size="small"
          @current-change="(p) => getHistory(store.state.settingProject.id, p)"
        />
      </el-tab-pane>

      <el-tab-pane
        label="知识库删除"
        v-if="store.state.projectType === 'myProjects'"
        name="ProjectDelete"
        lazy
      >
        <br />
        <el-popconfirm title="你想要删除该知识库吗？" @confirm="deleteProject">
          <template #reference>
            <el-button type="danger"> 删除知识库 </el-button>
          </template>
        </el-popconfirm>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>

  <el-dialog v-model="addMemberDialogVisible" title="添加成员">
    <el-form
      :model="addMemberFormData"
      :rules="addMemberFormRules"
      ref="addMemberForm"
    >
      <el-form-item prop="keyword">
        <el-input
          v-model.number="addMemberFormData.keyword"
          placeholder="搜索用户ID"
          maxlength="64"
        >
          <template #append>
            <el-button @click="searchMember">搜索</el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="5"
      class="m-0 p-0"
      v-if="addMember != null"
      v-loading="addMemberLoading"
    >
      <el-col :span="3">
        <el-avatar :src="addMember.avatarUrl" />
      </el-col>
      <el-col :span="6">
        <el-text>{{ addMember.nickname }}</el-text>
      </el-col>
      <el-col :span="4">
        <el-text>{{ addMember.id }}</el-text>
      </el-col>
      <el-col :span="7">
        <el-text>{{ addMember.email }}</el-text>
      </el-col>
      <el-col :span="4">
        <el-text type="primary" v-if="addMember.invite != null">
          已邀请，待同意
        </el-text>
        <el-text type="primary" v-else-if="memberInProject">
          已进入知识库
        </el-text>
        <el-button
          type="primary"
          plain
          v-else
          size="small"
          @click="inviteToProject"
          >邀请
        </el-button>
      </el-col>
    </el-row>

    <el-row v-else v-loading="addMemberLoading">
      <el-col>
        <el-empty description="查无此人" />
      </el-col>
    </el-row>

    <template #footer>
      <el-button type="primary" @click="addMemberDialogVisible = false">
        关闭
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>